/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        int sum = 0;
        return dfs(sum, root);
    }

    int dfs(int sum, TreeNode* node)
    {
        sum *= 10;
        sum += node->val;
        if (node->right == nullptr && node->left == nullptr)
        {
            return sum;
        }

        int ret = 0;
        if (node->left) ret += dfs(sum, node->left);
        if (node->right) ret += dfs(sum, node->right);

        return ret;
    }
};